import com.mit.web.business.proxy.DesignProxy;
import com.mit.web.business.remote.IInvokeResponder;
import com.mit.web.config.Constants;
import com.mit.web.event.ClickGridCheckBoxEvent;
import com.mit.web.event.PopWinCloseEvent;
import com.mit.web.util.DataFormatUtil;
import com.mit.web.util.LogUtil;
import com.mit.web.util.Validator;
import com.mit.web.view.component.monitor.IProgressMonitor;
import com.mit.web.view.design.TemplateDetailWindow;
import com.mit.web.vo.design.TemplatePartVO;
import com.mit.web.vo.design.TemplateVO;

import flash.events.Event;
import flash.events.MouseEvent;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.events.MenuEvent;
import mx.logging.ILogger;
import mx.resources.ResourceManager;
import mx.rpc.events.ResultEvent;
import mx.utils.StringUtil;

import org.flexunit.runner.Result;



[Bindable] private var _template:TemplateVO;
private var _proxy:DesignProxy = DesignProxy.getInstance();
private var _pm:IProgressMonitor;
private var _logger:ILogger;
private var _referTemplateId:int;

public function set template(t:TemplateVO):void{
	_template = t;
}
//加载纸样清单
private function loadDetailsHandler(e:FlexEvent):void{
	_logger = LogUtil.getLogger(this);

	var id:int = _template.id;
	var rsp:IInvokeResponder = _proxy.getTemplateDetails(id);
	rsp.addResultListener(loadResultHandler);
	rsp.addFaultListener(exceptionHandler);
	
	dg.addEventListener(ClickGridCheckBoxEvent.GRID_CHECKBOX_CLICK, gridItemSelected);
	
}

private function loadResultHandler(e:ResultEvent):void{
	var lst:ArrayCollection = e.result as ArrayCollection;
	if(lst){
		_template.parts = lst;
		dg.validateNow();
	}
}

private function gridItemSelected(event:Event):void{
	var hasItemSelected:Boolean = false;
	for each(var o:Object in _template.parts){
		if(o.isSelected){
			hasItemSelected = true;
			break;
		}
	}
	btn_removeRow.enabled = hasItemSelected;
}

//增加一行
protected function btn_newRow_clickHandler(event:MouseEvent):void
{
	var newItem:TemplatePartVO = new TemplatePartVO();
	newItem.templateId = _template.id;
	_template.parts.addItem(newItem);
	dg.editedItemPosition = {columnIndex:1, rowIndex:(_template.parts.length - 1)};
}
//移除选中的行
private function btn_removeRow_clickHandler(event:MouseEvent):void{
	removeSelectedItemFromList(_template.parts);
	dg.validateNow();
	event.currentTarget.enabled = false;
}
//点击保存
private function doSave(event:MouseEvent):void{
	//Validate
	//必须输入制版人
	if(lst_worker.selectedIndex == -1){
		showRequiredErrorTip( lst_worker);
		event.preventDefault();
		return;
	}
	if(chk_status.selectedValue == Constants.CLOSE){
		//Datagrid可以为空，因为用户有需要删除完现有记录并保存！此时，系统应该删除原有的数据。
		//但是，datagrid为空时，不能将状态设置为已完成。
		//And，所有的片数的尺寸必须输入，才能设置为已完成	
		var dataComplete:Boolean = true;
		if(_template.parts){
			for each(var part:TemplatePartVO in _template.parts){
				if(Validator.isNullOrBlank(part.name)
					|| Validator.isNullOrBlank(part.measure)){
					dataComplete = false;
					break;
				}
			}
		}
		
		if(_template.parts == null || _template.parts.length < 1 || !dataComplete){
			showErrorTip("样板尺寸未输入完整时，状态不能设置为已完成", chk_status);
			event.preventDefault();
			return;
		}
	}

	
	
	//assemble vo
	_template.state = chk_status.selectedValue;	
	//if(lst_worker.selectedItem)
		_template.worker = lst_worker.selectedId;
		_template.workerName = lst_worker.selectedItem.label;
	//else
	//	_template.worker = 0; 
	//	_template.workerName = null;
	
	var rsp:IInvokeResponder = _proxy.saveTemplate(_template);
	rsp.addFaultListener(exceptionHandler);
	rsp.addResultListener(saveResultHandler);
	
}
//保存成功派发事件
private function saveResultHandler(event:ResultEvent):void{
	var rtn:TemplateVO = event.result as TemplateVO;
	var e:PopWinCloseEvent = new PopWinCloseEvent(PopWinCloseEvent.SAVED);
	e.args = {workerName:_template.workerName, 
		state:_template.state, 
		partCount: _template.parts.length,
		worker:_template.worker,
		lastUpdatedTime:rtn.lastUpdatedTime}
	e.msg = ResourceManager.getInstance()
		.getString(Constants.BUNDLE_COMMON,"info.common.saved",[_template.style.code]);
	this.dispatchEvent(e);
	closeWindow(this);	
}
//查找是否有可以导入的其他样板
private function loadImportable(event:FlexEvent):void{
	var rsp:IInvokeResponder = _proxy.getTemplatesByStyle(_template.styleId, Constants.CLOSE, _template.id);
	rsp.addFaultListener(exceptionHandler);
	rsp.addResultListener(loadReferencedTemplateHandler);
}

private function loadReferencedTemplateHandler(event:ResultEvent):void{
	var refer:ArrayCollection = event.result as ArrayCollection;
	if(refer && refer.length > 0){		
		menu_import.dataProvider = refer;		
		btn_import.enabled = true;
	}else{
		btn_import.enabled = false;
	}
}
//导入菜单的LabelFunction
private function importLabelFunction(item:Object):String{

	var i:TemplateVO = item as TemplateVO;
	var type:String = DataFormatUtil.toTemplateTypeDisplayFormat(i.type);
	return i.size.concat(" ", type);
}
//选择导入的样板
private function confirmImport(event:MenuEvent):void{

	var i:TemplateVO = event.item as TemplateVO;
	_referTemplateId = i.id;
	Alert.show("尺码资料将会被导入的数据所取代，你确认要导入吗？",
		ResourceManager.getInstance().getString(Constants.BUNDLE_COMMON,"label.message.info"),
		Alert.YES|Alert.CANCEL, null	, doImport,null,Alert.CANCEL);
}

//读取所选样板的尺码清单
private function doImport(event:CloseEvent):void{
	if(event.detail == Alert.YES){
		var rsp:IInvokeResponder = _proxy.getTemplateDetails(_referTemplateId);
		rsp.addResultListener(importDetailsHandler);
		rsp.addFaultListener(exceptionHandler);
	}
}

//用导入的清单取代现在的清单
private function importDetailsHandler(event:ResultEvent):void{
	var refer:ArrayCollection = event.result as ArrayCollection;
	_template.parts = new ArrayCollection();
	for each(var referVO:TemplatePartVO in refer){
		var replicatedItem:TemplatePartVO = new TemplatePartVO();
		replicatedItem.templateId = _template.id;
		replicatedItem.name = referVO.name;
		replicatedItem.measure = referVO.measure;
		_template.parts.addItem(replicatedItem);
	}
	dg.validateNow();
}